package tools

import (
	"context"
	"github.com/aceld/zinx/ziface"
	"google.golang.org/grpc/metadata"
	"math/rand"
)

func MakeCtxFromConnection(conn ziface.IConnection) context.Context {
	if conn == nil {
		return context.Background()
	}
	token, err := conn.GetProperty("token")
	if err != nil {
		return context.Background()
	}
	md := metadata.Pairs("token", token.(string))
	return metadata.NewOutgoingContext(context.Background(), md)
}

// GenerateDrawRandNum 区间：前闭后开 不能从0开始 会重复
func GenerateDrawRandNum(min, max, sum int) ([]int32, error) {
	// 生成区间随机数组
	var nums []int32
	for i := 0; i < sum; i++ {
		if min >= max || min == 0 || max == 0 {
			return append(nums, int32(max)), nil
		}
		nums = append(nums, int32(rand.Intn(max-min)+min))
	}
	return nums, nil
}

// 根据时间戳返回一个小于1的小数，时间越早值越大（2的14次方/现在距离1970的天数（精确到秒））
func CreateDecimalByTimeStamp(timeStamp int64) float64 {
	return (1 << 14) / (float64(timeStamp) / float64(3600*24))
}
